import { User } from '@libs/db/models/User.model';
import { Body, Controller, Get, Post, UseGuards } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { AuthGuard } from '@nestjs/passport';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { ReturnModelType, DocumentType } from '@typegoose/typegoose';
import { InjectModel } from 'nestjs-typegoose';
import { CurrentUser } from './current-user.decorator';
import { LoginDto } from './dto/login.dto';
import { RegisterDto } from './dto/register.dto';

@Controller('auth')
@ApiTags('用户')
export class AuthController {

    constructor(
        private jwtService: JwtService,
        @InjectModel(User) private userModel: ReturnModelType<typeof User>
    ){ }

    @Post('register')
    @ApiOperation({ summary: '注册' })
    async register(@Body()dto: RegisterDto){

        const { username, password } = dto
        const user = await this.userModel.create({
            username,
            password
        })

        return user ? {
            status: 201,
            message: '注册成功'
        } : {
            status: 404,
            message: '注册失败'
        }
    }

    @Post('login')
    @ApiOperation({ summary: '登录' })
    @UseGuards(AuthGuard('local'))
    async login(@Body()dto: LoginDto, @CurrentUser() user: DocumentType<User>){

        return {
            token: this.jwtService.sign(String(user._id)),
            state: {
                status: 201,
                message: '登录成功'
            }
        }
    }

    @Post('logout')
    @ApiOperation({ summary: '注销' })
    async logout(){
        return {
            status: 201,
            message: '注销成功'
        }
    }

    @Get('user')
    @ApiOperation({ summary: '获取个人信息' })
    @UseGuards(AuthGuard('jwt'))
    @ApiBearerAuth()
    async user(@CurrentUser() user: DocumentType<User>){
        return user
    }
}
